package lowijs.XfireClient.packet;

import lowijs.XfireClient.*;
import lowijs.XfireClient.event.*;
import lowijs.XfireClient.util.Util;

public class ReceiveMessagePacket extends Packet {
	public static final int MSGTYPE_IM = 0x00;
	public static final int MSGTYPE_CHATAUTH = 0x02;
	public static final int MSGTYPE_TYPING = 0x03;
	
	private byte[] sid = new byte[16];
	private byte peermsg;
	private int msgtype;
	private int imindex;
	
	private final FriendManager fm = FriendManager.getInstance();
		
	public ReceiveMessagePacket(byte[] data) {
		System.arraycopy(data, 8, sid, 0, 16);
		peermsg = data[35];
		msgtype = Util.intFromBytes(data, 43, 4);
		
		switch(msgtype) {
		case MSGTYPE_IM: // we have to ack this, so save some data
			if (peermsg == 0x02) // we just sent an IM, no need to ack the ack
				break;
			imindex = Util.intFromBytes(data, 56, 4);
			byte[] imbytes = new byte[fromLowHigh(data[64], data[65])];
			System.arraycopy(data, 66, imbytes, 0, imbytes.length);
			
			Friend f = fm.getFriendBySid(sid);
			IM im = new IM(f.getNick(), new String(imbytes));
			f.receiveIM(im);
			
			EventManager.fireEvent(new ReceiveImEvent(im, f));
			break;
		case MSGTYPE_CHATAUTH: // we have to ack this?
			break;
		case MSGTYPE_TYPING:
			Friend typingfriend = fm.getFriendBySid(sid);
			EventManager.fireEvent(new FriendTypingEvent(typingfriend));
			break;
		}
	}
	
	public byte[] getSid() {
		return sid;
	}
	
	public int getMessageType() {
		return msgtype;
	}
	
	public int getImIndex() {
		return imindex;
	}
}
